<template>
  <a-input :value="titleField" @click="openModal" />
</template>
<script setup>
import { createApp, getCurrentInstance, h, nextTick, ref, shallowRef } from "vue";
import UnitSelectModal from "@/views/cwqs/UnitSelectModal.vue";

defineOptions({ name: "UitSelect" });
const props = defineProps({
  titleField: {
    type: String,
    default: undefined
  },
  value: {
    type: String,
    default: undefined
  }
});
const emits = defineEmits(["update:titleField", "update:value"]);
const instance = getCurrentInstance();

function openModal() {
  const refUnitSelectModal = shallowRef();
  const div = document.createElement("div");
  let node = () => h(UnitSelectModal,
    {
      value: props.value,
      titleField: props.titleField,
      ref: refUnitSelectModal,
      onChange({ keys, titles }) {
        emits("change", keys);
        emits("update:value", keys);
        emits("update:titleField", titles);
      },
      onClose: () => {
        setTimeout(() => {
          app.unmount();
          nextTick(div.remove);
        }, 300);
      }
    }, {});
  const app = createApp(node);
  for (let componentsKey in instance.appContext.components) {
    app.component(componentsKey, instance.appContext.components[componentsKey]);
  }
  for (let componentsKey in instance.appContext.directives) {
    app.directive(componentsKey, instance.appContext.directives[componentsKey]);
  }
  app.mount(div);
  nextTick(() => {
    refUnitSelectModal.value.openModal()
  })
}
</script>
